class Lily
	require 'cgi/session'

	class Session
		def initialize(req, userid, password)
			@req, @userid, @password = req, userid, password
		end

		def authorized
			if @req.params['mode'][0] == 'auth'
				if login()
					set_cookie()
				else
					false
				end
			else
				read_cookie()
			end
		end


		private

		def login
			(@req.params['userid'][0] == @userid && \
				@req.params['password'][0] == @password)
		end

		def set_cookie
			begin
				session = CGI::Session.new(@req, 'new_session' => false)
				session.delete
			rescue ArgumentError
			end

			session = CGI::Session.new(@req, 'new_session' => true)
			session['userid'] = @userid
			session.close
		end

		def read_cookie
			begin
				session = CGI::Session.new(@req, 'new_session' => false)
			rescue ArgumentError
			end

			(session) ? session['userid'] : nil
		end
	end

end

def auth
	return unless @editable_extension.index(@options.flavour)

	session = Lily::Session.new(@cgi, @userid, @password)

	if session.authorized()
	else
		@options.flavour = 'auth'
	end
end
